<?php
class comment {

	private static $config = '';

	/**
	 * 载入配置文件
	 * @param Array $config
	 */
	public static function initConfig($config) {
		self::checkConfig($config);
		self::set('config',  $config);
		
	}
	
	/**
	 * 检查载入的配置的格式是否正确
	 * @param Array $config
	 */
	private static function checkConfig($config) {
		if(!is_array($config))
			self::debug('$config must be array when init($config)', __LINE__);
		if(empty($config))
			self::debug('$config is empty when init($config)', __LINE__);
	}
	
	/**
	 * 获取类属性
	 * @param String $key
	 */
	public static function get($key) {
		$key = trim($key);
		
		if(!in_array($key, array_keys(self::getVars())))
			self::debug('unknow preperty $'.$key);
		
		return self::$$key;
	}
	
	/**
	 * 设置属性值
	 * @param String $key
	 * @param mixed $value
	 */
	public static function set($key, $value) {
		$key = trim($key);

		if(!in_array($key, array_keys(self::getVars())))
			self::debug('unknow preperty $'.$key);

		self::$$key = $value;
		
	}
	
	/**
	 * 返回由类的默认属性组成的数组
	 * @return Array
	 */
	public static function getVars() {
		return get_class_vars(get_class());
	}
	
	/**
	 * 打印debug信息
	 * @param mixed $msg
	 */
	private static function debug($msg) {
		die(json_encode(array('msg'=>$msg)));			
	}
	
	/**
	 * execute sql
	 * @param String $sql
	 * @param String $mode r for read , w for write
	 * 
	 */
	private static function sqlQuery($sql) {
		return db::query($sql);
	}
	
	private static function sqlInsert($sql) {
		return db::exec($sql);
	}
	
	public static function exec() {
		$c = self::$config;
		//self::debug($c);
		if ($c['req']['act']=='showList' && $c['req']['pag']) {
			$total = self::getTotal();
			$pag = intval($c['req']['pag']) === 0 ? 1 : intval($c['req']['pag']);
			if ($pag > $total)
				$pag = 1;
			
			$list = self::getList();
			$pager = self::pager($total, $pag, $c['limit']);
			echo json_encode(array('pager' => $pager, 'tol' => $total, 'list' => $list));
			exit;
		}elseif ($c['req']['act']=='postComment') {
			self::insert();
		}
		
	}
	
	/*
	 * 总数
	*/
	public static function getTotal() {
		$c = self::$config;
		$sql = '';
		$sql .= "SELECT count(`{$c['fields']['primaryKey']}`) AS `tol` FROM {$c['table']} ";
		$sql .=" WHERE  `{$c['fields']['foreignKey']['key']}`='{$c['fields']['foreignKey']['value']}' ";
		
		$sql .= self::getCondition()." LIMIT 1";

		$res = self::sqlQuery($sql);

		return intval($res[0]['tol']);
	}
	
	private static function getCondition() {
		$c = self::$config;
		if(isset($c['condition']) && !empty($c['condition']))
			return ' AND '.$c['condition'];
		else return '';
	}
	
	/*
	 * 列表
	*/
	public static function getList() {
		
		$c = self::$config;
		$pag = $c['req']['pag'];
		$pag = intval($pag) ? intval($pag) : 1;
		$start = ($pag-1)*$c['limit'];

		$sql = '';
		$sql .= "SELECT * FROM  {$c['table']} ";
		$sql .= " WHERE {$c['fields']['foreignKey']['key']}='{$c['fields']['foreignKey']['value']}'  ";
		$sql .= self::getCondition()." ORDER BY `ctime` DESC LIMIT {$start}, {$c['limit']} ";
	//self::debug($sql);
		
		$res = self::sqlQuery($sql);
		//D($res);
		if(is_array($res) && !empty($res)) {
			foreach($res as $k=>$v) {
				$res[$k]['ctime'] = date('Y-m-d H:i:s', $v['ctime']);
			}
		}
		return $res;
	}
	
	/**
	 * 分页
	 * @param string $url
	 * @param int $total
	 * @param int $page
	 * @param int $limit
	 * @return string pager
	 */
	private static function pager($total,$page,$limit=20){
		$ceil = ceil($total/$limit);
		$ceil >1 && $ceil_limit=5;
		if($ceil >1 && $page>=5){
			$ceil_limit=10;
		}
		if($page>=8){
			$ceil-$page >10? $st=$page-5:$st=$ceil-10;
			$ceil_limit += $st-1;
			if($ceil - $page <8){
				$st = $page-2;
				$ceil_limit = $ceil;
			}
			if($ceil - $page ==10){
				$st = $page-2;
				$ceil_limit =$st+9;
			}
		}else {
			$st=1;
		}
		$ceil <$ceil_limit && $ceil_limit=$ceil;
		$spage = '';
		for ($st;$st<=$ceil_limit;$st++){
			if ($page == $st || (empty($page) && $page==$st-1)) {
				$page==0&&$page=1;
				$spage .="<font>[$page]</font>&nbsp;";
			}else
				$spage .= "<a rel='{$st}'><font>[$st]</font></a>&nbsp;";
		}
	
		if($page>=$ceil){
			$npage = "<font>[已到尾页]</font>";
		}else {
			$npage = "<a rel='".($page+1)."'>[下一页]</a>";
			$npage .= "<a rel='".$ceil."'>[到尾页]</a>";
		}
		$ppage = ($page>7) ? "<a rel='1'>[回首页]</a>" : '';
		return $ceil>1?$ppage.$spage.$npage:$spage;
	}
	
	private static function answer_is_right($answer, $cookiename) {
		//echo json_encode(array('a'=>$answer, 'c'=>$_COOKIE[$cookiename]));exit;
		$right= intval($_COOKIE[$cookiename]);
		$answer=intval($answer);
		if($right === $answer) return true;
		else return false;
	}
	
	
	/*
	 * 插入评论
	*/
	public static function insert() {
		$c = self::$config;
		
		$keys = $values = '';
		foreach($c['fields'] as $k=>$v) {
			if($k=='primaryKey') continue;
			
			if($k=='foreignKey') {
				$keys .= $v['key'];
				$values .= $v['values'];
			}else{
				$keys .= "`{$v}`, ";
				$values .= "'".strip_tags($c['req'][$v])."', ";
			}
		}
		$keys = rtrim($keys, ', ');
		$values = rtrim($values, ', ');
		$sql = "INSERT INTO {$c['table']} ({$keys}) VALUES ($values)";
		self::debug($sql);
		self::execSQL($sql, 'w');
		exit;
	}
	
	/**
	 * 加载模板
	 */
	public static function load() {
		$c = self::$config;
		$tpl = file_get_contents($c['commentPATH'].'/comment.tpl');
		$dl = '<{';
		$dr = '}>';
		$searchArr = array(
			'COMMENT_CSS',
			'COMMENT_RAND',
			'COMMENT_PAGE',
			'COMMENT_COOKIE',
		);		
		$replace = array(
			$c['commentURL'].'/static/comment.css',
			$c['commentURL'].'/rand.php',
			$c['pageURL'],
			$c['cookiename'],
		);
		$search = array();
		for($i=0; $i<count($searchArr); $i++) {
			$search[] = $dl.$searchArr[$i].$dr;
		}
		$tpl = str_replace($search, $replace, $tpl);
		echo $tpl;
	}
	
}

?>